#ifndef POLYGONVOLUME_H_
#define POLYGONVOLUME_H_

#include <stdio.h>

namespace Geometry
{
	struct vertex
	{
		float x;
		float y;
		float z;
	};

	#define POLYGONVOLUME_VERSION	1

	typedef struct POLYGONVOLUMEHEADER
	{
		short version;
		unsigned int vertexCount;
		float minZ;
		float maxZ;
	} polygonVolumeHeader_t;

	typedef struct POLYGONVOLUMEMANAGERHEADER
	{
		unsigned int polygonCount;
	} polygonVolumeManagerHeader_t;

#define RANDOM_GEN_ATTEMPTS		100
	float RandomFloatRange(float min,float max);
	int RandomIntRange(int min,int max);

	class PolygonVolume
	{
	public:
		PolygonVolume();
		~PolygonVolume();

		void AllocateVertexes(const unsigned int count);
		bool DumpToFile(const char *filename);
		bool DumpToFile(FILE* fp);
		bool IsPointInside(vertex point);

		vertex GetRandomPoint();
		int GetVertexCount();

		void PrintVertexes();

		void SetVertexAt(const unsigned int index,vertex value);
		void SetVertices(vertex* vertices,unsigned int count);
		void SetZBounds(float minZ,float maxZ);

		static PolygonVolume* LoadFromFile(const char *filename);
		static PolygonVolume* LoadFromFile(FILE* fp);
	private:
		int EdgesCrossed(vertex test);
		void CalculateBoundingBox();

		unsigned int _vertexCount;
		short _version;
		float _minZ,_maxZ;
		vertex* _vertices;

		//bounding box
		float _minX,_maxX;
		float _minY,_maxY;
	};

	class PolygonVolumeManager
	{
	public:
		PolygonVolumeManager();
		~PolygonVolumeManager();

		void AllocatePolygons(unsigned int count);
		bool DumpToFile(const char* filename);
		void Print();
		bool TwoPointsInSamePolygon(vertex p1,vertex p2);
		bool TwoPointsInSamePolygon(float x1,float y1,float z1,float x2,float y2,float z2);

		PolygonVolume* GetPolygon(const unsigned int index);

		static PolygonVolumeManager* LoadFromFile(const char *filename);
	private:
		void DeallocatePolygons();

		unsigned int _polygonCount;
		PolygonVolume** _polygons;
	};
}

#endif /* POLYGONVOLUME_H_ */
